<?php
/**
 * 随机字符
 * @param int $length 长度
 * @param string $type 类型
 * @param int $convert 转换大小写 1大写 0小写
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
function random($length = 6, $type = 'number', $convert = 0)
{

    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) $type = 'number';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;

}

/**
 * 返回两个字符串之间的字符串
 * @param string $str 长度
 * @param string $beginstr 开始字符串
 * @param string $endstr 结束字符串
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
function cut_between_str($str, $beginstr, $endstr)
{

    $begin = strpos($str, $beginstr) + strlen($beginstr);
    $end = strpos($str, $endstr);
    $e = $end - $begin;
    return substr($str, $begin, $e);

}

/**
 * 所有用到密码的不可逆加密方式
 * @param string $password
 * @param string $salt
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
function encrypt($password, $salt)
{
    return md5(md5($password) . md5($salt));
}


/**
 * curl访问
 * @param string $url
 * @param string $type
 * @param boolean $data
 * @param string $err_msg
 * @param int $timeout
 * @param array $cert_info
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
function curl($url, $type = 'GET', $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
{

    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }
    $option = array();
    if ($type == 'POST') {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url . '&' . $data : $url . '?' . $data;
        }
    }
    $option[CURLOPT_URL] = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS] = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT] = $timeout;
    //设置证书信息
    if (!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT] = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE] = $cert_info['cert_type'];
    }
    //设置CA
    if (!empty($cert_info['ca_file'])) {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
    } else {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
    }
    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    // error_log
    if ($curl_no > 0) {
        if ($err_msg !== null) {
            $err_msg = '(' . $curl_no . ')' . $curl_err;
        }
    }
    return $response;

}

/**
 * 返回多久前
 * @param null $time
 * @return false|string
 * @author rainfer <1055213284@qq.com>
 */
function time_tran($time = NULL)
{

    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 （秒）
    $y = date('Y', $time) - date('Y', time());//是否跨年
    switch ($t) {
        case $t == 0:
            $text = '刚刚';
            break;
        case $t < 60:
            $text = $t . '秒前'; // 一分钟内
            break;
        case $t < 60 * 60:
            $text = floor($t / 60) . '分钟前'; //一小时内
            break;
        case $t < 60 * 60 * 24:
            $text = floor($t / (60 * 60)) . '小时前'; // 一天内
            break;
        case $t < 60 * 60 * 24 * 3:
            $text = floor($time / (60 * 60 * 24)) == 1 ? '昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time); //昨天和前天
            break;
        case $t < 60 * 60 * 24 * 30:
            $text = date('m月d日 H:i', $time); //一个月内
            break;
        case $t < 60 * 60 * 24 * 365 && $y == 0:
            $text = date('m月d日', $time); //一年内
            break;
        default:
            $text = date('Y年m月d日', $time); //一年以前
            break;
    }
    return $text;
}

/**
 * 成功返回json数据
 * @param int $code
 * @param string $msg
 * @param array $data
 * */
function json_success_data($msg = '', $data = [], $code = 200)
{
    if (!is_numeric($code)) {
        return '';
    }

    $result = array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    );

    return json_encode($result, JSON_UNESCAPED_UNICODE);

}

/**
 * 成功返回json提示消息
 * @param int $code
 * @param string $msg
 * @param array $data
 * */
function json_success_msg($msg = '', $code = 200)
{

    if (!is_numeric($code)) {
        return '';
    }

    $result = array(
        'code' => $code,
        'msg' => $msg,
    );

    return json_encode($result, JSON_UNESCAPED_UNICODE);

}

/**
 * 成功返回json提示消息
 * @param int $code
 * @param string $msg
 * @param array $data
 * */
function json_error_msg($msg = '', $code = 400)
{
    if (!is_numeric($code)) {
        return '';
    }

    $result = array(
        'code' => $code,
        'msg' => $msg,
    );

    return json_encode($result, JSON_UNESCAPED_UNICODE);

}

/**
 * 生成文章摘要
 *
 * @access public
 * @param string $str 待处理文章内容
 * @param int $length 要截取的长度
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
if (!function_exists('fetch_summary')) {

    function fetch_summary($str, $length)
    {

        // 还原html标记
        $str = htmlspecialchars_decode($str);
        // 删除html标记
        $str = strip_tags(str_ireplace('&nbsp;', ' ', $str));
        // // 将多个相连的空格缩减为1个
        // $str = preg_replace('/[ ]{2,}/', '', $str);
        $pattern = '/\s/';//去除空白
        $str = preg_replace($pattern, '', $str);
        // $suffix 截断显示字符  判断是否加省略号
        $suffix = mb_strlen($str, 'utf8') > $length ? '..' : '';
        // 截取并返回处理后的字符串

        return mb_substr($str, 0, $length, 'utf-8') . $suffix;

    }

}

/**
 * 页面元素显示权限验证
 * @param $source_str
 * @param $length
 * @param string $dot
 * @return string
 * @author rainfer <1055213284@qq.com>
 */
if (!function_exists('pw_check')) {

    function pw_check($admin_id, $str)
    {

        if ($admin_id != 0) {
            $pw_arr = (new \app\console\model\Admin())::admin_powers($admin_id);
            if (!in_array($str, $pw_arr)) {
                return "style='display:none'";
            }
        }
        return;

    }

}

/**
 * 驼峰样式字符串转化下划线
 * @param string $controller
 * @return  string
 * @author rainfer <1055213284@qq.com>
 */
if (!function_exists('str_to_line_lowers')) {
    function str_to_line_lowers($controller)
    {

        return strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $controller));

    }

}

/**
 * 获取栏目名称
 * @param $source_str
 * @param $length
 * @param string $dot
 * @return string
 */
if (!function_exists('get_cate_name')) {

    function get_cate_name($id)
    {

        return (new \app\common\model\NewsCate())::where(['id' => $id])->cache(true)->value('cate_name');
    }

}

/**
 * 获取栏目banner
 * @param $source_str
 * @param $length
 * @param string $dot
 * @return string
 */
if (!function_exists('get_cate_banner')) {

    function get_cate_banner($id)
    {
        $model = new \app\common\model\NewsCate();
        $that = $model->where(['id' => $id])->field('cate_img,cate_path,cate_pid')->cache(true)->find();
        if ($that['cate_img'] || $that['cate_pid'] == 0) {
            return $that['cate_img'];
        }

        $cate_path_arr = explode('-', $that['cate_path']);
        $p_cate_banner = $model->where(['id' => $cate_path_arr[0]])->cache(true)->value('cate_img');
        return $p_cate_banner;
    }

}


/**
 * 广告显示
 * @param $adsp   广告位ID
 * @param $map  查询条件
 * @param $order
 * @param $limit
 * @param $field
 * @return s
 */
if (!function_exists('db_ads_list')) {

    function db_ads_list($adsp, $map = [], $order = 'sort asc,ads_id desc', $limit = 1, $field = null)
    {
        if ($field) {
            $field = 'ads_id,ads_name,ads_type' . ',' . $field;
        } else {
            $field = 'ads_id,ads_name,ads_type';
        }

        $order = empty($order) ? 'sort asc,ads_id desc' : $order;
        return (new \app\common\model\Ads())::where(['is_show' => 1, 'is_del' => 0, 'belong_adsp_id' => $adsp])->where($map)->order($order)->limit($limit)->field($field)->cache(true)->select();
    }

}


/**
 * 新闻
 * @param $id   栏目ID
 * @param $map  查询条件
 * @param $order
 * @param $limit
 * @param $field
 * @return s
 */
if (!function_exists('db_news_list')) {

    function db_news_list($id, $map, $order, $limit = 1, $field = null)
    {

        if ($field) {
            $field = 'id,news_title' . ',' . $field;
        } else {
            $field = 'id,news_title';
        }

        $order = empty($order) ? 'is_top desc,is_hot desc,sort asc,id desc' : $order;

        return (new \app\common\model\News())::where(['is_pass' => 1, 'is_del' => 0])->where('belong_id', 'in', $id)->where($map)->order($order)->limit($limit)->field($field)->cache(true)->select();
    }

}


/**
 * 子栏目
 * @param $cate_pid   父栏目ID
 * @param $order
 * @param $field
 * @return s
 */
if (!function_exists('db_son_cate_list')) {

    function db_son_cate_list($cate_pid, $order = null, $field = null)
    {

        if ($field) {
            $field = 'id,cate_name' . ',' . $field;
        } else {
            $field = 'id,cate_name';
        }
        $order = empty($order) ? 'sort asc,id asc' : $order;
        return (new \app\common\model\NewsCate())::where(['is_show' => 1, 'cate_pid' => $cate_pid])->order($order)->field($field)->cache(true)->select();
    }

}


/**
 * 随机推荐  相同栏目内容
 * $beside_id  排除ID
 * @param $belong_id   栏目ID
 * @param $order
 * @param $field
 * @return s
 */
if (!function_exists('db_news_catenews')) {

    function db_news_catenews($beside_id, $belong_id, $limit = 1, $field = null)
    {

        if ($field) {
            $field = 'id,news_title' . ',' . $field;
        } else {
            $field = 'id,news_title';
        }

        $list = (new \app\common\model\News())::where(['is_pass' => 1, 'belong_id' => $belong_id])->where('id', 'neq', $beside_id)->orderRaw('rand()')->limit($limit)->field($field)->select();
        if (count($list) < $limit) {
            $other_count = $limit - count($list);

            $other_list = (new \app\common\model\News())::where(['is_pass' => 1])->where('belong_id', 'in', '11,12,13,14,15,16,17,18')->where('id', 'neq', $beside_id)->orderRaw('rand()')->limit($other_count)->field($field)->select();

            $list = array_merge($list, $other_list);


        }

        return $list;

    }
}



 function output_base($code, $status, $result, $message) {
    header("Content-Type: application/json;");
    $data = [
        'code' => $code,
        'status' => strtoupper($status),
        'message' => $message,
        'data' => $result,
    ];
    return json($data);
}

/**
 * 接口成功返回
 */
 function outsucc($result = [], $message = '接口请求成功', $status = 'success') {
    return output_base(200, $status, $result, $message);
}


/**
 * 接口失败反馈
 */
  function outfail($message = "操作失败", $status = "fail", $result = []) {
    return output_base(200, $status, $result, $message);
}
/**
 * 操作调用展示反馈
 */
  function outerr($code, $message = "操作失败", $status = "fail", $result = []) {
    return output_base($code, $status, $result, $message);
}
/**
 * 列表数据处理
 */
 function get_listpage_data($list, $count, $pageCount, $page = 1, $pageSize = 20) {
    return [
        'page' => $page,
        'count' => $count,
        'pagesize' => $pageSize,
        'pagecount' => $pageCount,
        'list' => $list,
    ];
}

/**
 * 程序执行失败
 */
 function output_throw($code, $message, $trace) {
    return output_base($code, 'fail', $trace, $message);
}



